// d:\company-projects\shenye-dy-applet\pages\login\login.js
import {
  loginDyAuthorization,
  customerLoginDy
} from '../../api/login'
const handleAuthorize = require('../../utils/handleAuthorize')
const app = getApp()
Page({
  data: {
    linkJump: '',
    dyCode: '', //抖音code
    linkJump: '', //跳转链接
    isGou: false, //是否勾选协议
    loginType: 0, // 0:一键登录  1：手机号码登录
  },

  onLoad: function (options) {
    if (!handleAuthorize.isEmpty(options.linkJump)) {
      this.setData({
        linkJump: options.linkJump
      })
    }
  },
  onShow() {
    this.getCode()
  },
  // 手机号码登录
  loginTel() {
    handleAuthorize.preventActive(() => {
      this.setData({
        loginType: 1
      })
      if (!this.data.isGou) {
        const popup = this.selectComponent('#popup');
        popup.open();
        return
      }
      if (!handleAuthorize.isEmpty(this.data.linkJump)) {
        tt.navigateTo({
          url: `/pages/login/login_phone/login_phone?linkJump=${this.data.linkJump}`,
        });
      } else {
        tt.navigateTo({
          url: `/pages/login/login_phone/login_phone`,
        });
      }
    })
  },
  //勾选协议
  checkView() {
    this.data.isGou = !this.data.isGou
    this.setData({
      isGou: this.data.isGou
    })
  },
  // 获取code
  getCode() {
    let that = this;
    tt.login({
      success: function (res) {
        if (res.code) {
          // console.log('res.code',res.code)
          that.setData({
            dyCode: res.code
          })
        } else {
          console.log('获取code失败', res.errMsg)
        }
      }
    })
  },
  //未勾选时点击
  checkFalseView() {
    this.setData({
      loginType: 0
    })
    const popup = this.selectComponent('#popup');
    popup.open();
  },
  //获取手机号
  async getPhoneNumberHandler(e) {
    // console.log(e);
    // console.log(e.detail.iv);
    // console.log(e.detail.encryptedData);

    this.setData({
      loginType: 0,
      isGou: true
    })
    this.selectComponent('#popup').close()
    if (e.detail.encryptedData == undefined) { //用户拒绝时
      return
    }
    var data = {
      code: this.data.dyCode,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
    }
    // 开发appid 测试删除掉
    data.appId = app.globalData.appId
    data.loginType = app.globalData.loginType

    tt.showLoading({
      title: '登录中'
    })
    try {
      const res = await customerLoginDy(data);
      // console.log('login_res', res)
      tt.hideLoading();
      // tt.setStorageSync('isTemporary', res.result.isTemporary);
      tt.setStorageSync('token', res.result);
      tt.showToast({
        title: '登录成功',
        icon: 'success'
      });
      // 判断是否有链接转跳
      if (!handleAuthorize.isEmpty(this.data.linkJump) && !handleAuthorize.isEmpty(tt.getStorageSync('linkJump'))) {
        setTimeout(() => {
          var curRoute = tt.getStorageSync('linkJump')
          // 防止微信静默 登录url 出错
          if (curRoute.indexOf('/pages/login/login') > -1) {
            curRoute = '/pages/index/index'
          }
          if(curRoute.indexOf('back=1') > -1){
            tt.navigateBack({
              delta:1
            });
          }else if(curRoute.indexOf('/pages/index/index') > -1 || curRoute.indexOf('/pages/my/my') > -1 || curRoute.indexOf('/pages/integralTask/integralTask') > -1){
            tt.reLaunch({
              url: curRoute
            })
          }else{
            tt.redirectTo({
              url: curRoute
            })
          }
        }, 800)
      } else {
        setTimeout(() => {
          tt.reLaunch({
            url: '/pages/index/index'
          })
        }, 800)
      }
    } catch {
      this.getCode()
    } finally {

    }
  },
  // 不同意协议
  noAgreeWith() {
    this.setData({
      isGou: false
    })
    this.selectComponent('#popup').close()
  },
  // 同意协议
  agreeWith() {
    this.setData({
      isGou: true
    })
    this.selectComponent('#popup').close()
    this.loginTel()
  },
  // 抖音账号一键登录
  tiktokAccount() {
    var that = this
    tt.getUserProfile({
      success(res) {
        that.loginTiktokAccount()
      },
      fail(res) {
        that.getCode()
      },
    });
  },
  async loginTiktokAccount() {

    var data = {
      dyCode: this.data.dyCode
    }
    // 开发appid 测试删除掉
    data.appId = app.globalData.appId
    data.loginType = app.globalData.loginType

    tt.showLoading({
      title: '登录中'
    })
    try {
      const res = await loginDyAuthorization(data);
      // console.log('login_res', res)
      tt.hideLoading();
      tt.setStorageSync('isTemporary', res.result.isTemporary);
      tt.setStorageSync('token', res.result.token);
      // 是否临时账户 true为是 false 否
      if (res.result.isTemporary) {
        tt.showToast({
          title: '您暂未完成账号注册流程，请绑定手机号',
          icon: 'none'
        });
        // 
        setTimeout(() => {
          tt.navigateTo({
            url: `/pages/login/bind_phone/bind_phone?linkJump=${this.data.linkJump}`,
          });
        }, 1000)
      } else {
        tt.showToast({
          title: '登录成功',
          icon: 'success'
        });
        // 判断是否有链接转跳
        if (!handleAuthorize.isEmpty(this.data.linkJump) && !handleAuthorize.isEmpty(tt.getStorageSync('linkJump'))) {
          setTimeout(() => {
            var curRoute = tt.getStorageSync('linkJump')
            // var curRoute = JSON.parse(decodeURIComponent(tt.getStorageSync('linkJump')))
            // 防止微信静默 登录url 出错
            if (curRoute.indexOf('/pages/login/login') > -1) {
              curRoute = '/pages/index/index'
            }
            if(curRoute.indexOf('/pages/index/index') > -1 || curRoute.indexOf('/pages/my/my') > -1 || curRoute.indexOf('/pages/integralTask/integralTask')> -1){
              tt.reLaunch({
                url: curRoute
              })
            }else{
              tt.redirectTo({
                url: curRoute
              })
            }
          }, 800)
        } else {
          setTimeout(() => {
            tt.reLaunch({
              url: '/pages/index/index'
            })
          }, 800)
        }
      }

    } catch {
      this.getCode()
    } finally {

    }
  },
  // 跳转协议
  jumpAgreement(e) {
    var title = ''
    var type = e.currentTarget.dataset.type
    if (type == 1) {
      title = '神椰用户服务协议'
    } else {
      title = '神椰隐私保护协议'
    }
    tt.navigateTo({
      url: `/pages/agreement/agreement?type=${type}&title=${title}`,
    });
  },


  // 暂不登录
  jumpHome() {
    tt.reLaunch({
      url: '/pages/index/index'
    })
  },

})